﻿using FastCodeGeneration.Core.Framework;
using FastCodeGeneration.Entity;
using FastCodeGeneration.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FastCodeGeneration.Repository
{
    public class TemplateRepository : BaseRepository<Template>, ITemplateRepository
    {

        public List<Template> SelectDefault(string serverTemplate, string viewTemplate)
        {
            string[] templates = new string[] { serverTemplate, viewTemplate };
            return Context.Queryable<Template>().Where(e => e.ProjectId == null && templates.Contains(e.TemplateType)).ToList();
        }

        public bool DeleteByProjectId(int? projectId)
        {
            return this.Delete(e => e.ProjectId == projectId);
        }

        public IPage<Template> SelectByCondition(Condition condition)
        {
            QueryWrapper<Template> wrapper = this.getQueryWrapperByCondition(condition);
            if (condition.ExportAll)
            {
                condition.PageSize = 10000;
            }
            Page<Template> page = new Page<Template>(condition.PageIndex, condition.PageSize);
            int totalNumber = 0;
            if (wrapper.GetSugarParameters().Count > 0)
            {
                var sql = $"SELECT * FROM (SELECT t.*,p.Name as ProjectName FROM Template t LEFT JOIN Project p on t.project_id=p.Id) WHERE {wrapper.getSqlResult()}";
                page.Records = Context.SqlQueryable<Template>(sql).AddParameters(wrapper.GetSugarParameters())
                    .ToPageList(page.PageIndex, page.PageSize, ref totalNumber);
            }
            else
            {
                var sql = $"SELECT * FROM (SELECT t.*,p.Name as ProjectName FROM Template t LEFT JOIN Project p on t.project_id=p.Id)";
                page.Records = Context.SqlQueryable<Template>(sql).ToPageList(page.PageIndex, page.PageSize, ref totalNumber);
            }
            page.TotalCount = totalNumber;
            return page;
        }

        public List<Template> SelectByProjectId(int? projectId)
        {
            return Context.Queryable<Template>().Where(e => e.ProjectId == projectId).ToList();
        }

    }
}
